"""
HiAgent数据模型
"""
from typing import List, Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum


class AppType(Enum):
    """应用类型枚举"""
    CHAT = "Chat"
    COMPLETION = "Completion"
    WORKFLOW = "Workflow"
    CHATFLOW = "ChatFlow"


class AgentMode(Enum):
    """智能体模式枚举"""
    SINGLE = "Single"
    MULTI = "Multi"


class ProcessRuleFileType(Enum):
    """文件类型枚举

    根据 HiAgent API 文档（docs/v2.1.0-llmops-app-server-api_doc.md）：
    ProcessRuleFileType 的正确枚举值：
    - 0 = Normal（普通非结构化文档：TXT、PDF、DOC、DOCX等）
    - 1 = Structure（结构化文档：XLS、XLSX、CSV等）
    - 2 = JSON（JSON文档）
    - 3 = Markdown（Markdown文档）

    注意：所有普通文档（TXT、PDF、DOCX等）都应该使用 ProcessRuleFileType=0
    """
    NORMAL = 0      # 普通文档（TXT、PDF、DOC、DOCX等）
    STRUCTURE = 1   # 结构化文档（XLS、XLSX、CSV等）
    JSON = 2        # JSON文档
    MD = 3          # Markdown文档

    # 保留旧的别名以兼容，但都指向正确的值
    TXT = 0         # 纯文本 -> Normal
    PDF = 0         # PDF -> Normal
    DOCX = 0        # Word文档 -> Normal
    XLSX = 1        # Excel -> Structure
    CSV = 1         # CSV -> Structure

    @classmethod
    def from_extension(cls, ext: str) -> int:
        """根据文件扩展名获取对应的枚举值

        Args:
            ext: 文件扩展名（不区分大小写）

        Returns:
            对应的整数枚举值
        """
        ext = ext.lower().lstrip('.')

        # 映射表 - 所有普通文档都返回 0
        mapping = {
            'txt': 0,      # Normal
            'text': 0,     # Normal
            'pdf': 0,      # Normal
            'doc': 0,      # Normal
            'docx': 0,     # Normal
            'md': 3,       # Markdown
            'markdown': 3, # Markdown
            'json': 2,     # JSON
            'jsonl': 2,    # JSON
            'xls': 1,      # Structure
            'xlsx': 1,     # Structure
            'csv': 1,      # Structure
        }

        return mapping.get(ext, 0)  # 默认返回 Normal (0)


@dataclass
class AppBriefInfo:
    """应用简要信息"""
    app_id: str
    name: str
    description: str
    app_type: AppType
    icon: Optional[str] = None
    background: Optional[str] = None
    image: Optional[str] = None
    workspace_id: Optional[str] = None
    created_time: Optional[str] = None
    updated_time: Optional[str] = None
    is_published: Optional[bool] = None
    agent_mode: Optional[AgentMode] = None


@dataclass
class AppCenterBriefInfo:
    """应用中心简要信息"""
    app_id: str
    name: str
    description: str
    app_type: AppType
    icon: Optional[str] = None
    background: Optional[str] = None
    image: Optional[str] = None
    category_id: Optional[str] = None
    category_name: Optional[str] = None
    author: Optional[str] = None
    publish_time: Optional[str] = None
    is_favorite: Optional[bool] = None
    usage_count: Optional[int] = None
    rating: Optional[float] = None


@dataclass
class AppCenterCategory:
    """应用中心分类"""
    category_id: str
    name: str
    description: Optional[str] = None
    icon: Optional[str] = None
    sort_order: Optional[int] = None
    app_count: Optional[int] = None


@dataclass
class AppCenterRecentlyUsedBriefInfo:
    """应用中心最近使用简要信息"""
    app_id: str
    name: str
    description: str
    app_type: AppType
    icon: Optional[str] = None
    background: Optional[str] = None
    image: Optional[str] = None
    last_used_time: Optional[str] = None


@dataclass
class ListOption:
    """列表选项"""
    page: Optional[int] = 1
    page_size: Optional[int] = 20
    sort_field: Optional[str] = None
    sort_order: Optional[str] = None  # "asc" or "desc"


@dataclass
class ListAppCenterFilter:
    """应用中心列表筛选条件"""
    category_id: Optional[str] = None
    app_types: Optional[List[AppType]] = None
    keyword: Optional[str] = None
    is_published: Optional[bool] = None
    published_agent_mode: Optional[AgentMode] = None
    app_ids: Optional[List[str]] = None
    exclude_app_ids: Optional[List[str]] = None


@dataclass
class ListAppBriefsFilter:
    """应用列表筛选条件"""
    app_types: Optional[List[AppType]] = None
    keyword: Optional[str] = None
    is_published: Optional[bool] = None
    agent_mode: Optional[AgentMode] = None


@dataclass
class PersonalAgent:
    """个人智能体"""
    app_id: str
    name: str
    description: str
    app_type: AppType
    icon: Optional[str] = None
    background: Optional[str] = None
    image: Optional[str] = None
    workspace_id: Optional[str] = None
    created_time: Optional[str] = None
    updated_time: Optional[str] = None
    agent_mode: Optional[AgentMode] = None
    is_runnable: Optional[bool] = None
    config: Optional[Dict[str, Any]] = None


@dataclass
class Plugin:
    """插件信息"""
    plugin_id: str
    name: str
    description: str
    category_id: Optional[str] = None
    category_name: Optional[str] = None
    icon: Optional[str] = None
    version: Optional[str] = None
    author: Optional[str] = None
    install_count: Optional[int] = None
    rating: Optional[float] = None
    is_installed: Optional[bool] = None


@dataclass
class PluginCategory:
    """插件分类"""
    category_id: str
    name: str
    description: Optional[str] = None
    icon: Optional[str] = None
    plugin_count: Optional[int] = None


@dataclass
class KnowledgeBase:
    """知识库"""
    kb_id: str
    name: str
    description: str
    workspace_id: str
    icon: Optional[str] = None
    created_time: Optional[str] = None
    updated_time: Optional[str] = None
    document_count: Optional[int] = None
    size: Optional[int] = None
    status: Optional[str] = None


@dataclass
class WorkflowStatus(Enum):
    """工作流状态枚举"""
    PUBLISHED = "Published"
    UNPUBLISHED = "Unpublished"


@dataclass
class WorkflowRuntimeStatus(Enum):
    """工作流运行状态枚举"""
    INIT = "Init"
    SUCCEED = "Succeed"
    FAILED = "Failed"
    RUNNING = "Running"


@dataclass
class WorkflowInputSchema:
    """工作流输入参数定义"""
    name: str
    desc: str
    type: int  # 0=string, 2=boolean, 3=number
    required: Optional[bool] = None
    default: Optional[str] = None


@dataclass
class Workflow:
    """工作流信息"""
    workflow_id: str
    name: str
    description: str
    status: Optional[str] = None  # Published/Unpublished
    runtime_status: Optional[str] = None  # Init/Succeed/Failed/Running
    input_schema: Optional[List[WorkflowInputSchema]] = None
    icon: Optional[str] = None
    dirty: Optional[bool] = None
    create_time: Optional[str] = None
    create_user: Optional[str] = None
    update_time: Optional[str] = None
    update_user: Optional[str] = None
    workspace_id: Optional[str] = None


@dataclass
class APIResponse:
    """API响应基础类"""
    status_code: int
    status_message: str
    data: Optional[Any] = None

    @property
    def is_success(self) -> bool:
        return self.status_code == 0